import urllib.parse

from django.shortcuts import render
from django.views.generic import ListView
from django.db.models import Count

from .models import Auth, Subscriptions, Resources

import logging
logger = logging.getLogger(__name__)
logger.success = lambda msg, *args, **kwargs: logger.log(25, msg, *args, **kwargs)

# Create your views here.
class HomeListView(ListView):
    """Renders the home page, with a list of all messages."""
    model = Auth

    def get_context_data(self, **kwargs):
        context = super(HomeListView, self).get_context_data(**kwargs)
        return context


class SubscriptionListView(ListView):
    model = Subscriptions

    def get_context_data(self, **kwargs):
        context = super(SubscriptionListView, self).get_context_data(**kwargs)
        return context

def resource_count(request, group_by='location', auth='auth', subscription='subscription'):
    subscription = urllib.parse.unquote(subscription)

    auth_list = Auth.objects.values_list('name', 'display_name')

    queryset = Resources.objects.all() if auth == 'auth' else Resources.objects.filter(subscription__auth__name=auth)
    queryset_sub = Subscriptions.objects.all() if auth == 'auth' else Subscriptions.objects.filter(auth__name=auth)

    subscription_list = queryset_sub.values_list('name', flat=True)
    
    queryset = queryset if subscription == 'subscription' else queryset.filter(subscription__name=subscription)
    # 最后返回的时候要把内部的元素从字典转为列表，去掉字典的key。
    # 因为这个key传到前端是无法从字典取到key中的值的。字典提取值必须提供key的字符串，不能是变量
    # 也不能用字典的get方法，访问方法调用:
    # https://docs.djangoproject.com/zh-hans/4.0/ref/templates/language/#accessing-method-calls
    # Django 有意限制了模板中的逻辑处理量，可以调方法但是“不能传参”。数据应该在视图中计算，然后传递给模板显示。
    # 意思就是在这里把方法调用完成拿到结果传到前端，而不是在前端再去调用方法。
    # 过滤器是可以带参数的，所以还可以，编写自定义的模板过滤器：
    # https://docs.djangoproject.com/zh-hans/4.0/howto/custom-template-tags/#writing-custom-template-filters
    queryset = queryset.filter(del_time__isnull=True).values(group_by)\
        .annotate(count=Count('id')).order_by('-count')

    return render(request, "resource/resource.html", {
        # 由于无法通过变量去取字典的值，这里转成列表，弃掉key只要value，用列表的下标来取值
        # 或者方案二，把动态的key的名称统一改成固定的名称，前端可以通过字符串来取值
        'resources': [ list(q.values()) for q in queryset ],
        'group_by': group_by,
        'auth': auth,
        'subscription': subscription,
        'auth_list': auth_list,
        'subscription_list': subscription_list,
        })


def log_console(request):
    """在终端展示各个日志级别的打印效果"""
    logger.critical('打印测试消息: critical log message.')
    logger.error('打印测试消息: error log message.')
    logger.warning('打印测试消息: warning log message.')
    logger.success('打印测试消息: success log message.')
    logger.info('打印测试消息: info log message.')
    logger.debug('打印测试消息: debug log message.')
    logger.log(0, '打印测试消息: notset(0) log message.')
    return render(request, "resource/logger.html")

def about(request):
    return render(request, "resource/about.html")

def contact(request):
    return render(request, "resource/contact.html")